package com.fs.base.utils;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

/**
 * 安全工具类，可以进行数据的加密和解密，并且可以完成对象的加密和解密
 *
 */
public class Md5Utils {
	public static String md5(String password) throws NoSuchAlgorithmException {
		MessageDigest md = MessageDigest.getInstance("MD5");
		md.update(password.getBytes());
		return new BigInteger(1,md.digest()).toString(16);
	}
	
	public static String md5(String username,String password) throws NoSuchAlgorithmException {
		MessageDigest md = MessageDigest.getInstance("MD5");
		md.update(username.getBytes());
		md.update(password.getBytes());
		return new BigInteger(1,md.digest()).toString(16);
	}
	
	public static String generateToken(String path,Map<String,String> params) throws NoSuchAlgorithmException {
		String url = markUrl(path, params);
		return Md5Utils.md5(url);
	}
	
	private static String markUrl(String baseUrl, Map<String, String> params){
		if(params != null && params.size() > 0) {
			baseUrl = baseUrl + "?" + makeQueryString(params);
        }
		return baseUrl;
	}
	
	public static String makeQueryString(Map<String, String> params) {
        StringBuffer query = new StringBuffer();
        if(params != null) {
            List<Entry<String, String>> list = new ArrayList<Entry<String, String>>(params.entrySet());
            Collections.sort(list, new Comparator<Entry<String, String>>() {
				@Override
				public int compare(Entry<String, String> o1, Entry<String, String> o2) {
					return o1.getKey().compareTo(o2.getKey());
				}
            });
            for(int i=0; i < list.size(); ++i) {
            	Entry<String, String> mapping = list.get(i);
                if(i > 0) {
                    query.append("&");
                }
                query.append((String)mapping.getKey() + "=" + (String)mapping.getValue());
            }
        }
        return query.toString();
    }
	
}
